package com.vgemv.jsutilitysdk.Display.JsDisplayManagerGamma;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Rect;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;

import androidx.appcompat.widget.ContentFrameLayout;

import com.vgemv.jsutilitysdk.geometry.JsGeometryManager;
import com.vgemv.jsutilitysdk.log.JsLogManager;
import com.vgemv.jsutilitysdk.Reminder.JsReminderManager;

import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 显示到Activity的PhoneWindow上.
 *
 * 1,WindowManager添加一个view,其实是在WindowManager的一个FrameLayout中添加了这个view.
 */
public class JsDisplayManagerGamma {

    //用来保存conentView和其parent,即该activity的R.id.content.
    static public  HashMap<View,ContentFrameLayout> map_parent = new HashMap<>();
    static public  HashMap<View,ViewTreeObserver.OnGlobalLayoutListener> map_observer = new HashMap<>();
    static public  HashMap<View,JsDisplayManagerGammaCallback> map_callback = new HashMap<>();
    //用来保存contentView和其显示的style
    static public  HashMap<View,JsDisplayStyleGamma> map_style = new HashMap<>();
    //用来保存contentView和取消的定时器timer.
    static public  HashMap<View,Timer> map_timer = new HashMap<>();

    //加载提示view
    static public View mView_loadingReminder;
    //加载提示view的显示次数
    static public int mi_loadingCount;

    //将LoadingReminderView显示到屏幕中间


    static public  void displayLoadingReminder(Activity activity) {
        if (mi_loadingCount == 0) {
            if(mView_loadingReminder == null) {
                mView_loadingReminder = JsReminderManager.getLoadingRemindStandard1(activity);
            }
            mi_loadingCount = 1;

            //默认用110dp.居中显示.
            int size = JsGeometryManager.pixelFromDp(110);
            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(size,size);
            lp.addRule(RelativeLayout.CENTER_IN_PARENT);
            //loadingReminder的mask不能点击.
            JsDisplayStyleGamma style = new JsDisplayStyleGamma();
            style.isMaskViewClickable = false;
            display(activity,mView_loadingReminder,style,lp,null);
        } else {
            mi_loadingCount++;
        }
    }

    static public void undisplayLoadingReminder() {
        mi_loadingCount--;
        if (mi_loadingCount == 0) {
            undisplay(mView_loadingReminder);
        }
    }

    static  public void displayMessage(Activity activity,String message) {
        displayMessage(activity,message, JsReminderManager.JsMessageReminderType.Info);
    }


    static public void displayMessage (Activity activity,String message, JsReminderManager.JsMessageReminderType type ) {
        View messageReminder = JsReminderManager.getMessageReminderIl(activity,type,message);

        //默认用110dp.居中显示.
        int size = JsGeometryManager.pixelFromDp(110);
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        lp.addRule(RelativeLayout.CENTER_IN_PARENT);

        JsDisplayStyleGamma style = new JsDisplayStyleGamma();
        style.mI_duration = 3;

        display(activity,messageReminder,style,lp,null);
    }



    /**
     * 显示contentView到activity的R.id.content上.
     * @param activity
     * @param view
     * @param style
     * @param callback
     */
    static public void display(Activity activity, final View view, JsDisplayStyleGamma style, RelativeLayout.LayoutParams layoutParams, JsDisplayManagerGammaCallback callback) {
        if(style == null) {
            style = new JsDisplayStyleGamma();
        }
        map_style.put(view,style);
        final ContentFrameLayout frameLayout = getContentFrameLayout(activity);
        final RelativeLayout maskView = getMaskView(activity,style);
        ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        frameLayout.addView(maskView, lp);
        if(layoutParams != null) {
            maskView.addView(view,layoutParams);
        }
        else {
            maskView.addView(view);
        }

        //添加至map保存信息. 1个maskView对应1个wm.
        map_parent.put(view,frameLayout);
        if(callback != null) {
            map_callback.put(view, callback);
        }
        if(style.mb_isObserveKeybord) {
            addKeyboardObserver(maskView, view);
        }

        //隐藏的定时器
        if(style.mI_duration != null) {
            //这种不好,需要可以取消的方式.

            Timer timer = new Timer();
            map_timer.put(view,timer);
            TimerTask task = new TimerTask() {
                @Override
                public void run() {
                    undisplay(view);
                }
            };
            timer.schedule(task,style.mI_duration * 1000);
//            JsThreadManager.runInMainThreadDelayed(style.mI_duration * 1000, new Runnable() {
//                @Override
//                public void run() {
//                    undisplay(view);
//                }
//            });
        }
    }

    /**
     * 从Activity的R.id.content的View中移除contentView.
     * @param contentView
     */
    static public void undisplay(View contentView) {
        RelativeLayout maskView = (RelativeLayout)contentView.getParent();
        ContentFrameLayout frameLayout = map_parent.get(contentView);
        frameLayout.removeView(maskView);
//                Object o = map_observer.get(contentView);
//                if(o!= null) {
        map_observer.remove(contentView);
//                }
        maskView.removeAllViews();
        JsDisplayManagerGammaCallback callback = map_callback.get(contentView);
        if(callback != null) {
            callback.onUndisplay(contentView);
            map_callback.remove(contentView);
        }
        //清除style
        map_callback.remove(contentView);

        //Timer处理
        Timer timer_undisplay = map_timer.get(contentView);
        if(timer_undisplay != null) {
            timer_undisplay.cancel();
            map_timer.remove(contentView);
        }
    }

//    /**
//     * 使用PhoneWindow的windowmanager添加,效果不好.
//     * @param activity
//     * @param view
//     */
//    static public void display2(Activity activity, View view) {
//        final WindowManager windowManager = getActivityPhoneWindowManager(activity);
//
//        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
//
//        //window的内容对齐方式
//        lp.gravity = Gravity.CENTER;
//        lp.setTitle("sadff");
//
//
//        //设置要添加的View的大小
//        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
//        lp.height = WindowManager.LayoutParams.MATCH_PARENT;
//
//        //需要设置颜色格式,否则后面好像有问题.
//        lp.format = PixelFormat.RGBA_8888;
//
//        //这个window的alpha 1 是正常的,但是还是设置为255!!!
//        lp.alpha = 1f;
//        lp.dimAmount = 0.8f;
//
//        final LinearLayout maskView = getMaskView(activity);
//        windowManager.addView(maskView, lp);
//
//        JsThreadManager.runInMainThreadAtNextRunloop(new Runnable() {
//            @Override
//            public void run() {
//                Rect frame = new Rect();
//                maskView.getGlobalVisibleRect(frame);
//                JsLogManager.logc_d("JsDisplayManagerGamma",frame.toString());
//            }
//        });
//
////        maskView.addView(view);
//
//        //添加至map保存信息. 1个maskView对应1个wm.
////        map.put(maskView,windowManager);
//    }

    //添加到Activity的CotentView上,效果就不错了.
    static private ContentFrameLayout getContentFrameLayout(Activity activity) {
        Window window = activity.getWindow();
        ViewGroup vp = (ViewGroup) window.getDecorView();
        ContentFrameLayout frameLayout = vp.findViewById(android.R.id.content);
        return frameLayout;
    }


    /**
     * 生成maskView,每个contentView都要生成maskView.
     * @param context
     * @return
     */
    static private RelativeLayout getMaskView(Context context,JsDisplayStyleGamma style) {
        final RelativeLayout maskView = new RelativeLayout(context);
        maskView.setId(View.generateViewId());
        if(!style.mb_isShowMaskView) {
            maskView.setEnabled(false);
        }
        else {
            maskView.setBackgroundColor(Color.argb(60, 60, 60, 60));
            if(style.isMaskViewClickable) {
                maskView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //undisplay
                        //点击取消,保存草稿
                        View contentView = maskView.getChildAt(0);
                        undisplay(contentView);
                    }
                });
            }
        }
        return maskView;
    }




    static public WindowManager getActivityPhoneWindowManager(Activity activity) {
        Window window = activity.getWindow();
        WindowManager windowManager = window.getWindowManager();
        //状态栏半透明了
//        window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN| View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
//        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
//        window.setStatusBarColor(Color.TRANSPARENT);
//        window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        return windowManager;
    }

//    public void undisplayViewFromPhoneWindow(View view) {
//        Window window = mActivity.getWindow();
//        //这个vp实质上是一个FrameLayout;
//        ViewParent vp = mll_mask.getParent();
//        FrameLayout fl = (FrameLayout)vp;
//        fl.removeView(mll_mask);
//    }
//
//
//    public void undisplayViewFromPhoneWindowManager(View view) {
//        Window window = mActivity.getWindow();
//        WindowManager windowManager = window.getWindowManager();
//        windowManager.removeView(view);
//    }
//
//    public void removeKeyboardObserver() {
//        final View rootView = mActivity.getWindow().getDecorView().findViewById(android.R.id.content);
//        rootView.getViewTreeObserver().removeOnGlobalLayoutListener(mGlobalLayoutListener);
//    }
//
    static public void addKeyboardObserver(final View rootView, final View contentView) {
        ViewTreeObserver.OnGlobalLayoutListener globalLayoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect r1 = new Rect();
                Rect r2 = new Rect();
                //获取当前窗口实际的可见区域

                //1794,没有包含状态栏.
//                    int screenHeight = JsGeometryManager.getDevicePixelSize().getHeight();

                //JsGeometryManager.getDevicePixelSize().getHeight() = 1794.
                //contentView-getWindowVisibleDisplayFrame --> (0,63 - 1080,1794) 表示contentView在window的区域是这个.后面的那个点是有下家的坐标,而不是高度.
                //conentView.getBottom = 1731, getTop = 0,是自身的坐标系.
                //contentView.getGlobalVisibleRect (0,0,1080,1794), 感觉这个是真真的手机全屏的尺寸.

                //decorView-getWindowVisibleDisplayFrame --> (0,63 - 1080,1794)
                //decorView,top:0,bottom:1920. decorView的bottom是1920,怎么这么多???

                rootView.getWindowVisibleDisplayFrame(r1);
                //getDrawingRect getLocalVisibleRect
                //getHitRect getGlobalVisibleRect
                rootView.getGlobalVisibleRect(r2);
//                JsLogManager.logc_d("xx","display frame,top:%d,bottom:%d,height:%d",r.top,r.bottom,r.height());
//                JsLogManager.logc_d("xx","root view,top:%d,bottom:%d,height:%d",rootView.getTop(),rootView.getBottom(),rootView.getHeight());
                int raiseHeight = r2.bottom - r1.bottom;

                JsLogManager.logc_d("JsDisplayManagerGamma", "Raise height is %d", raiseHeight);
                RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) contentView.getLayoutParams();
                lp.setMargins(0, 0, 0, raiseHeight);
                contentView.setLayoutParams(lp);

            }
        };
        rootView.getViewTreeObserver().addOnGlobalLayoutListener(globalLayoutListener);
        map_observer.put(rootView, globalLayoutListener);
    }
}


